package biznussoft.metercor.fragments;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import biznussoft.metercor.MainActivity;
import biznussoft.metercor.R;
import biznussoft.metercor.entity.AccountModel;
import biznussoft.metercor.entity.ActivityModel;
import biznussoft.metercor.entity.TimeModel;
import biznussoft.metercor.listener.DialogListener;
import biznussoft.metercor.utils.CustomProgressDialog;
import biznussoft.metercor.utils.ExpandCollapseAnimation;
import biznussoft.metercor.utils.Session;

import com.google.gson.Gson;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class TimeMasterFragment extends Fragment implements OnClickListener{

	DialogListener listener;
	private CheckBox mBillable;
	private EditText etStartDate,etEndDate,etComments;
	private Spinner spType;
	private int mHeight1 = 0;
	private LinearLayout timeLayout,newTimeLayout;
	private RestClient client;
	private ActivityModel mobel;
	private Dialog progressDialog;
	private String strId;
	private int position;
	private ImageView addTime,imgStartNotes,imgEndNotes,btSave;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.time_master_fragment, null);
	}



	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		listener = (DialogListener) getActivity();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		imgStartNotes = (ImageView) getView().findViewById(R.id.startNotes);
		imgEndNotes = (ImageView) getView().findViewById(R.id.endNotes);
		imgStartNotes.setOnClickListener(this);
		imgEndNotes.setOnClickListener(this);

		client = MainActivity.mActivity.client;
		addTime = (ImageView) getView().findViewById(R.id.addTime);
		timeLayout = (LinearLayout) getView().findViewById(R.id.sectionsLayout1);
		newTimeLayout = (LinearLayout) getView().findViewById(R.id.lllayoutnewtimeMode);
		btSave = (ImageView) getView().findViewById(R.id.save);
		btSave.setOnClickListener(this);
		etStartDate = (EditText) getView().findViewById(R.id.etStartDate);
		spType = (Spinner) getView().findViewById(R.id.spType);
		etEndDate = (EditText) getView().findViewById(R.id.etEndDate);
		etComments = (EditText) getView().findViewById(R.id.etComments);
		mBillable = (CheckBox) getView().findViewById(R.id.editCheckBillable);
		Bundle i = getArguments();
		progressDialog = CustomProgressDialog.getInstance().createProgressDialog(getActivity());
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.show();
		position = i.getInt("Position");
		getDetails(position);
		addTime.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				addNewTime();				
			}
		});
	}







	public void addNewTime(){
		timeLayout.setVisibility(View.GONE);
		newTimeLayout.setVisibility(View.VISIBLE);


	}



	public void  getDetails(int position){

		mobel = ServiceOrderActivityRecordsFragment.list.get(position);
		Session.sFconnectActivity =mobel.getActivityName();
		strId = mobel.getId();
		Log.i("NCS","strId  " +strId);
		getTime(strId);


	}

	public void setStartDate(String date){

		etStartDate.setText(date);
	}
	public void setEndDate(String date){

		etEndDate.setText(date);               

	}

	public void getTime(String  id){

		try{
			timeLayout.setVisibility(View.VISIBLE);
			newTimeLayout.setVisibility(View.GONE);
			String serviceOrder = "SELECT Name,Id,FConnect__Billable__c,FConnect__Type__c,FConnect__Activity1__c,Activity_Name__c,FConnect__Technician__c,FConnect__Cost__c,FConnect__Comments__c,End_Date_Time__c,Start_Date_Time__c,FConnect__Displsay_Duration__c From FConnect__Time__c where FConnect__Activity__c ="+"'"+id+"'";
			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), serviceOrder);
			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try { 
						progressDialog.dismiss();
						Log.i("NCS","result is  :"+result);
						JSONObject jsonObject1 = new JSONObject(result.asString());
						JSONArray jsonArray = jsonObject1.getJSONArray("records");
						ArrayList<TimeModel>  timeList = new ArrayList<TimeModel>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							if(!jsonArray.isNull(i)){
								TimeModel bean = _gson.fromJson(jsonArray.getString(i), TimeModel.class);
								timeList.add(bean);
							}
						}                        

						showRecords(timeList);

					} catch (Exception e) {
						Log.i("NCS","Exception is  :"+e.getMessage());
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});

		} catch (Exception e) {
			Log.i("NCS","Exception  in time is  :"+e.getMessage());
		}



	}

	public void showRecords(ArrayList<TimeModel> list){
		
		for (int i = 0; i < list.size(); i++) {                   

			TimeModel donor = list.get(i);
			View view = getActivity().getLayoutInflater().inflate(R.layout.time_displaydata, timeLayout,false);
			TextView	mName = (TextView) view.findViewById(R.id.tvContactLastName);
			TextView	mType = (TextView) view.findViewById(R.id.tvContactTitle);
			TextView 	mCost = (TextView) view.findViewById(R.id.tvContactEmail);
			TextView 	mGender = (TextView) view.findViewById(R.id.tvContactPhone);
			TextView 	mStart = (TextView) view.findViewById(R.id.tvStartDate);
			TextView 	mEnd = (TextView) view.findViewById(R.id.tvEndDate);

			mName.setText(donor.getName());
			mType.setText(donor.getType());
			mCost.setText(donor.getCost());
			mGender.setText(donor.getDuration());
			mStart.setText(donor.getStartDate());
			mEnd.setText(donor.getEndDate());

			timeLayout.addView(view);


			final ImageView iv_expandcollapse = (ImageView) view.findViewById(R.id.iv_CollapseExpand);
			final LinearLayout sectionitemsParent = (LinearLayout) view.findViewById(R.id.llSectionItems);
			iv_expandcollapse.setImageResource(R.drawable.expand);
			sectionitemsParent.setVisibility(View.GONE);


			iv_expandcollapse.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {

					if (sectionitemsParent.getVisibility() == View.VISIBLE) {// Collapse
						ExpandCollapseAnimation collapseAnimation = new ExpandCollapseAnimation(sectionitemsParent, 1000, 1, iv_expandcollapse);
						mHeight1 = collapseAnimation.getHeight();
						iv_expandcollapse.startAnimation(collapseAnimation);
					} else{// Expand
						ExpandCollapseAnimation expandAnimation = new ExpandCollapseAnimation(sectionitemsParent, 1000, 0, iv_expandcollapse);
						if (mHeight1 == 0) {
							mHeight1 = getSectionitemsHeight();
						}
						expandAnimation.setHeight(mHeight1);
						iv_expandcollapse.startAnimation(expandAnimation);
					}
				}

				private int getSectionitemsHeight() {
					return (int) (4 * getResources().getDimension(R.dimen.section_item_height));
				}
			});
		}}




	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.startNotes:
			Session.sStartTime = true;
			Session.sEndTime = false;
			Session.sActivity = false;
			Session.sTime = false;
			Session.sExpense = false;
			Session.sNewTime = true;
			Session.sNewExpenses = false;
			listener.nextDialog("date");
			break;
		case R.id.endNotes:
			Session.sStartTime = false;
			Session.sEndTime = true;
			Session.sActivity = false;
			Session.sTime = false;
			Session.sExpense = false;
			Session.sNewTime = true;
			Session.sNewExpenses = false;
			listener.nextDialog("date");
			break;
		case R.id.save:
			insertTime();
			break;

		default:
			break;
		}

	}

	public void insertTime(){
		progressDialog = CustomProgressDialog.getInstance().createProgressDialog(getActivity());
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.show();
		boolean flag = mBillable.isChecked();

		String objectType = "FConnect__Time__c";                                                                       
		HashMap<String, Object> fields = new HashMap<String, Object>();
		fields.put("FConnect__Activity__c",strId);  
		fields.put("FConnect__Technician__c",Session.sTechnicianId);
		fields.put("FConnect__Comments__c",etComments.getText().toString());
		fields.put("Start_Date_Time__c",etStartDate.getText().toString());
		fields.put("End_Date_Time__c",etEndDate.getText().toString());
		fields.put("FConnect__Type__c",spType.getSelectedItem().toString());
		fields.put("FConnect__Billable__c",flag);

		try {
			RestRequest restRequest = RestRequest.getRequestForCreate(getString(R.string.api_version),objectType,fields);


			client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {     
						Log.i("TPT","onSuccess");
						progressDialog.dismiss();
						etComments.setText("");
						etStartDate.setText("");
						etEndDate.setText("");
						mBillable.setChecked(false);
						TimeMasterFragment newFragment1 = new TimeMasterFragment();
						Bundle args = new Bundle();
						args.putInt("Position", position);
						newFragment1.setArguments(args);
						FragmentTransaction transaction1 = getActivity().getSupportFragmentManager().beginTransaction();
						transaction1.replace(R.id.menus, newFragment1);                 
						transaction1.commit();    
					}                                
					catch (Exception e) {
						Log.i("TPT","Exception is   :"+e.getMessage());                      
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});
		} 
		catch (Exception e) {
			Log.i("NCS","Exception is   :"+e.getMessage());

		}



	}



}
